#!/bin/bash

# 定义日志文件
LOG_FILE="$HOME/install_r.log"

echo "This script will install R and its dependencies on your system. The log of this installation process will be saved in $LOG_FILE"

# 保存当前工作目录
pushd . >/dev/null

# 设置工作目录变量
WORK_DIR="$HOME/temp-for-r"
R_VERSION="R-4.4.1"
R_MAJOR_MINOR_VERSION=$(echo$R_VERSION | cut -d'.' -f1)

# 创建工作目录并进入
mkdir -p "$WORK_DIR" && cd "$WORK_DIR" || exit

# 开始安装过程，并重定向输出到日志文件
{
    # 安装依赖包
    sudo yum install -y \
        gcc \
        gcc-c++ \
        gcc-gfortran \
        libgcc \
        openssl-devel \
        zlib-devel \
        automake \
        libtool \
        cmake \
        python3 \
        readline-devel \
        libcurl-devel

    # 检查 R 是否已经安装
    if ! type "R" >/dev/null 2>&1; then
        # 下载并安装 R
        wget "https://mirrors.ustc.edu.cn/CRAN/src/base/${R_MAJOR_MINOR_VERSION}/${R_VERSION}.tar.gz"
        tar -zxvf "${R_VERSION}.tar.gz" && cd "${R_VERSION}" || exit
        mkdir -p "$HOME/${R_VERSION}"
        ./configure \
            --prefix="$HOME/${R_VERSION}" \
            --enable-R-shlib \
            --enable-BLAS-shlib \
            --with-blas \
            --with-lapack \
            --with-x=no
        make -j "$(nproc)"
        make install

        echo "R install finished, now deploying..."
        # 配置环境变量
        {
            echo "export R_HOME=$HOME/${R_VERSION}"
            echo "export PATH=\$R_HOME/bin:\$PATH"
        } >>"$HOME/.bash_profile"

        # 激活环境变量
        source "$HOME/.bash_profile"
    else
        echo "R has already installed, skip install step"
    fi

    # 删除工作目录
    cd ~ || exit
    rm -rf "$WORK_DIR"

    # 再次刷新环境
    source "$HOME/.bash_profile"

    # 验证 R 是否安装成功
    if R --version >/dev/null 2>&1; then
        echo "R installation successfully, version as below:"
        R --version
    else
        echo "R installation failed, please check the log file $LOG_FILE for more details"
    fi

    echo "this script is finished"
} >>"$LOG_FILE" 2>&1

# 恢复之前的工作目录
popd >/dev/null || exit
